<?php

class Job extends BaseModel 
{

    public $res_id;
    public $system_id;
    public $output_name;
    public $query_select;
    public $query_condition;
    public $latest_start; 
    public $task_date;
    public $trigger_way;

    public $start_date;
    public $end_date;
    public $file_md5;

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'job';
    }

    public function rules()
    {
        if($this->job_type == JobType::Query) {
            $required = 'job_name, job_priority, query_select, query_condition, res_id, output_name';
        }
        elseif($this->job_type == JobType::Transfer) {
            $required = 'job_name, job_priority, job_frequency, res_id, system_id';
        }
        elseif($this->job_type == JobType::Compute) {
            $required = 'job_name, job_priority, job_frequency, workflow_name, trigger_way';
        }
        return array(
            array($required, 'required', 'message'=>'{attribute} 不能为空'),
        );
    }
    
	public function relations() {
		return array(
      		'user'	=>	array(self::BELONGS_TO, 'User', 'user_id', 'joinType' => 'INNER JOIN'),
        );
	}

    /**
     *
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'job_id' => '编号',
            'job_name' => '名称',
            'user_id' => '用户',
            'job_type' => '类型',
            'job_priority' => '优先级别',
            'job_frequency' => '运行周期',
            'submit_time' => '提交时间',
            'res_id'   => '资源名',
            'query_select'   => '查询列',
            'query_condition'   => '查询条件',
            'output_name'   => '查询结果',
            'system_id' =>  '导出到',
            'workflow_name' =>  '工作流',
            'latest_start' =>  '最晚开始时间',
            'task_date' =>  '基准时间',
            'trigger_way'=> '触发方式',
        );
    }

    public function search($type) {
        $criteria=new CDbCriteria;
        $criteria->compare('job_type', $type);
        $criteria->addCondition('state <> '. JobState::Removed);
        if(Yii::app()->user->role == Role::Normal) {
            $criteria->addCondition('user_id='. Yii::app()->user->id);
        }
        return new CActiveDataProvider('Job', array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'job_id DESC',
            ),
        ));
    }
    
    /**
     * @return string the URL that shows the detail of the task
     */
    public function getWorkflowUrl()
    {
        return Yii::app()->createUrl('workflow/index', array(
            'id'=>$this->workflow_name,
        ));
    }
}
